//
//  CloudMessage.swift
//  home
// 客户端与服务端通信消息格式
//
//  Created by Yun Zeng on 2019/8/4.
//  Copyright © 2019 Yun Zeng. All rights reserved.
//

import Foundation

class CloudMessage: Codable {
    var path: String
    var home: String?
    var method: Method?
    
    var session: String?
    var state: String?
    
    // 消息携带的json格式的数据
    private var _data: AnyJSONType?
    var data: Data? {
        get {
            return try? JSONEncoder().encode(self._data)
        }
        set {
            if (newValue != nil) {
                self._data = try? JSONDecoder().decode(AnyJSONType.self, from: newValue!)
            }
        }
    }
    
    private enum CodingKeys: String, CodingKey {
        case path
        case home
        case method
        case session
        case state
        case _data = "data"
    }
    
    // 创建消息
    init(path: String, method: CloudMessage.Method, data: Data?) {
        self.path = path
        self.method = method
        self.data = data
    }
    
    init<T>(path: String, method: Method, object: T) where T: Encodable {
        self.path = path
        self.method = method
        self.data = try? JSONEncoder().encode(object)
    }
    
    // 通过接收的数据创建消息
    init?(data: Data) {
        guard let msg = try? JSONDecoder().decode(CloudMessage.self, from: data) else {
            return nil
        }
        self.home = msg.home
        self.path = msg.path
        self.method = msg.method
        self._data = msg._data
        self.state = msg.state
        self.session = msg.session
    }
    
    // 消息JSON编码
    func encode() -> Data? {
        guard let data = try? JSONEncoder().encode(self) else {
            return nil
        }
        return data
    }
}


extension CloudMessage {
    enum Method: String, Codable {
        case post
        case get
        case put
    }
    
    public struct Path {
        public static let membership = "member"
        public static let login = "member/login"
        public static let logout = "member/logout"
        public static let heartbeat = "hb"
        public static let accessories = "accessories"
        public static let characteristic = "characteristic"
        public static let apnsInfo = "member/push/apns"
    }
}

// 消息错误类型
enum CloudMessageError: Error {
    case success
    case jsonFormatError
    case invalidParameter
}

// 调试输出
extension CloudMessage: CustomStringConvertible {
    var description: String {
        let data = try! JSONEncoder().encode(self)
        return String(bytes: data, encoding: .utf8)!
    }
}

